// 身份验证相关API

// 用户信息类型定义
export interface User {
  id?: string | number;
  username: string;
  nickname?: string;
  avatar?: string;
  role?: number; // 用户角色 1:超级管理员 2:管理员 3:普通用户
  [key: string]: any;
}

// API响应类型定义
export interface ApiResponse<T = any> {
  code: number;
  data?: T;
  msg?: string;
}

// 登录响应类型
export interface LoginResponse {
  token: string;
  user: User;
}

// 获取API基础URL
const getBaseUrl = (): string => {
  // 使用类型断言来避免TypeScript的类型检查错误
  const env = (import.meta as any).env || {};
  return env.VITE_API_BASE_URL || '';
}

// 登录接口
export const login = async (username: string, password: string): Promise<ApiResponse<LoginResponse>> => {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ username, password })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('登录请求失败:', error);
    throw error;
  }
}

// 获取当前用户信息
export const getCurrentUser = async (): Promise<ApiResponse<User>> => {
  try {
    const token = localStorage.getItem('token');
    
    if (!token) {
      throw new Error('未找到认证令牌');
    }
    
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/auth/current`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('获取用户信息失败:', error);
    throw error;
  }
}

// 检查是否已登录
export const isAuthenticated = (): boolean => {
  return !!localStorage.getItem('token');
}

// 注销
export const logout = (): void => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
}

// 获取存储的用户信息
export const getStoredUser = (): User | null => {
  const userJson = localStorage.getItem('user');
  if (userJson) {
    try {
      return JSON.parse(userJson);
    } catch (e) {
      console.error('解析用户信息失败:', e);
      return null;
    }
  }
  return null;
}

// 重置密码
export const resetPassword = async (username: string, oldPassword: string, newPassword: string): Promise<ApiResponse> => {
  try {
    const token = localStorage.getItem('token');
    
    if (!token) {
      throw new Error('未找到认证令牌');
    }
    
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/auth/resetPassword`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ 
        username, 
        oldPassword, 
        newPassword 
      })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('重置密码失败:', error);
    throw error;
  }
} 